package com.guchenbo.example.thread;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {
    public static void main(String[] args) throws InterruptedException {
        NamedThreadFactory threadFactory = new NamedThreadFactory("my thread-", false);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
                        threadFactory);
        //        executor.allowCoreThreadTimeOut(true);

        exception();
//        for (int i = 0; i < 10; i++) {
//            executor.submit(() -> {
//                while (!Thread.currentThread().isInterrupted()) {
//                    System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().isInterrupted());
////                    try {
////                        Thread.sleep(5000);
////                    } catch (InterruptedException e) {
//////                        System.out.println("线程被打断了，那我就退出了");
////                        e.printStackTrace();
//////                        break;
////                    }
//                    File file = new File("/tmp");
//                    System.out.println(file.isDirectory());
//                }
//            });
//        }
//
//        Uninterruptibles.sleepUninterruptibly(3L, TimeUnit.SECONDS);
//        //        while (!executor.isTerminated()) {
//        //            System.out.println(executor.getPoolSize());
//        //        }
//        executor.shutdownNow();
//        try {
//            // 等待线程池关闭，最多等待5分钟
//            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
//                // 如果等待超时，则打印日志
//                System.err.println("线程池未能在5分钟内完全关闭");
//            }
//        } catch (InterruptedException e) {
//            // 异常处理
//            e.printStackTrace();
//        }
//
//        System.out.println("end");
        //        while (true) {
        //
        //        }


    }

    private static void exception() {
        NamedThreadFactory threadFactory = new NamedThreadFactory("my thread-", false);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
                        threadFactory);
        for (int i = 0; i < 10; i++) {

            executor.execute(()->{
                if (new Random().nextBoolean()) {
                    throw new RuntimeException("error");
                }
                System.out.println("end");
            });
        }

    }
}
